<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/group.css">
    <title>Group4_UniHub</title>
</head>
<body>
    <div class="header">
      <h1>Group Management</h1>
    </div>
    <div class="row">
      <!--Row starting-->
      <div class="col-3 col-m-3 menu">
        <button class="Btn loginOutBtn">Log Out</button>
        <!-- <button class="Btn editProfileBtn">Edit My Profile</button> -->
        <ul>
          <li id="studentProfilesLink">Student Profiles</li>
          <li id="groupManagementLink">Group Management</li>
          <li id="campusNoticeboard">Campus Noticeboard</li>
        </ul>
      </div>
      <div class="col-7 col-m-9">
        <div class="search-container" id="searchContainer">
            <input type="text" id="searchInput" placeholder="Please enter information to search for groups">
            <button id="searchButton">search</button>
        </div>
        <button class="createGroup">Create Group</button>
        <!-- Group Table -->
        <div id="groupContainer">
            <table id="groupTable">
              <thead>
                <tr>
                  <th>GroupID</th>
                  <th>Name</th>
                  <th>Description</th>
                  <th>Type</th>
                  <th>AdminID</th>
                  <th>Privacy</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                <!-- Data will be inserted here by JavaScript -->
              </tbody>
            </table>
          </div>
        <!-- Edit Modal -->
        <div id="editModal" class="modal">
            <div class="modal-content">
                <span class="close">&times;</span>
                <form id="editForm">
                    <h2>Edit Group</h2>
                    <label>Group Name:</label>
                    <input type="text" id="groupName" name="groupName" required>
                    <label>Type:</label>
                    <select id="type" name="type" required>
                        <option value="Sports">Sports</option>
                        <option value="Artistic">Artistic</option>
                        <option value="Academic">Academic</option>
                        <option value="Entertainment">Entertainment</option>
                    </select>
                    <label for="privacy">Privacy:</label>
                    <select id="privacy" name="privacy" required>
                        <option value="Public">Public</option>
                        <option value="Private">Private</option>
                    </select>
                    <label>Description:</label>
                    <textarea id="description" name="description" required></textarea>
                    <input type="hidden" id="groupId" name="groupId" required>
                    <button type="submit">Save Changes</button>
                </form>
            </div>
         </div>
        <!-- Create Group Modal -->
        <div id="createModal" class="modal">
            <div class="modal-content">
                <span class="close">&times;</span>
                <h2>Create New Group</h2>
                <form id="createForm">
                    <label>Group Name:</label>
                    <input type="text" id="createGroupName" name="groupName" required>
                    <label>Type:</label>
                    <select id="createType" name="type" required>
                        <option value="Sports">Sports</option>
                        <option value="Artistic">Artistic</option>
                        <option value="Academic">Academic</option>
                        <option value="Entertainment">Entertainment</option>
                    </select>
                    <label for="createPrivacy">Privacy:</label>
                    <select id="createPrivacy" name="privacy" required>
                        <option value="Public">Public</option>
                        <option value="Private">Private</option>
                    </select>
                    <label>Description:</label>
                    <textarea id="createDescription" name="description" required></textarea>
                    <button type="submit">Create Group</button>
                </form>
            </div>
        </div>

        </div>
      <div class="col-2 col-m-12 filter-container">
        <form>
            <label><input type="checkbox" name="Sports" value="Sports">Sports</label><br>
            <label><input type="checkbox" name="Artistic" value="Artistic">Artistic</label><br>
            <label><input type="checkbox" name="Academic" value="Academic">Academic</label><br>
            <label><input type="checkbox" name="Entertainment" value="Entertainment">Entertainment</label><br>
            <button type="button" onclick="filterResults()" class="filterBtn">Filter</button>
        </form>
      </div>
    
    </div>
    <!--Row ending-->

    <footer>
        <p>Group4 : Gina22083649_Yani22083647_Quinn22083651_Iris22083648</p>
    </footer>
    <script>
    // Display all the group
    document.addEventListener('DOMContentLoaded', function() {
    fetch('/groupList')
        .then(response => response.json())
        .then(data => populateTable(data))
        .catch(error => console.error('Error fetching group data:', error));

    document.getElementById('searchButton').addEventListener('click', function() {
        const keyword = document.getElementById('searchInput').value;
        fetch(`/groupSearch?keyword=${encodeURIComponent(keyword)}`)
            .then(response => response.json())
            .then(data => populateTable(data))
            .catch(error => console.error('Error fetching search results:', error));
    });

    //Define the filterResults function
    function filterResults() {
        const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
        const selectedTypes = Array.from(checkboxes).map(checkbox => checkbox.value);

        const typesString = selectedTypes.join(',');

        fetch(`/groupFilter?types=${encodeURIComponent(typesString)}`)
            .then(response => response.json())
            .then(data => {
                populateTable(data);
            })
            .catch(error => console.error('Error fetching filtered results:', error));
    }

    //Bind the filterResults function to the button's onclick event
    document.querySelector('.filterBtn').addEventListener('click', filterResults);

    function populateTable(data) {
        const tableBody = document.querySelector('#groupTable tbody');
        tableBody.innerHTML = ''; 
        data.forEach(group => {
            const row = document.createElement('tr');
            const actionCell = document.createElement('td');

            const userId = localStorage.getItem('userId');
            const isAdmin = group.AdminID === userId;

            if (isAdmin) {
            //If you are an administrator, display the "Edit" and "Delete" buttons
                const editButton = document.createElement('button');
                editButton.textContent = 'Edit';
                editButton.className = 'edit-btn';
                editButton.dataset.groupId = group.GroupID;
                editButton.addEventListener('click', handleEditClick);

                const deleteButton = document.createElement('button');
                deleteButton.textContent = 'Delete';
                deleteButton.className = 'delete-btn';
                deleteButton.dataset.groupId = group.GroupID;
                deleteButton.addEventListener('click', handleDeleteClick);

                actionCell.appendChild(editButton);
                actionCell.appendChild(deleteButton);
            } else {
            //If not an administrator, check if the user is a member of the group
                const button = document.createElement('button');
                button.textContent = 'Join'; 
                button.className = 'join-btn'; 
                button.dataset.groupId = group.GroupID;
                button.dataset.isAdmin = isAdmin ? 'true' : 'false';

                button.addEventListener('click', handleActionClick);

                actionCell.appendChild(button);

                checkUserMembership(group.GroupID, button);
            }
            row.innerHTML = `
            <td>${group.GroupID}</td>
            <td>${group.GroupName}</td>
            <td>${group.Description}</td>
            <td>${group.Type}</td>
            <td>${group.AdminID}</td>
            <td>${group.Privacy}</td>
            `;
            row.appendChild(actionCell);
            tableBody.appendChild(row);
        });
    }
    
    function handleDeleteClick(event) {
        const groupId = event.target.dataset.groupId;
        const userId = localStorage.getItem('userId');

        if (confirm(`Are you sure you want to delete group ${groupId}?`)) {
            fetch(`/deleteGroup/${groupId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Group deleted successfully');
                    location.reload();
                } else {
                    alert(data.message);
                }
            })
            .catch(error => console.error('Error deleting group:', error));
        }
    }

    function checkUserMembership(groupId, button) {
        const userId = localStorage.getItem('userId');

        fetch(`/isMember?groupId=${groupId}&userId=${userId}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        })
        .then(response => {
            if (!response.ok) {
                console.error(`HTTP error! status: ${response.status}`);
                return response.json().then(data => Promise.reject(data));
            }
            return response.json();
        })
        .then(data => {
            if (data && data.isMember !== undefined) {
                updateButtonState(button, data.isMember);
            } else {
                console.error('Unexpected response format:', data);
            }
        })
        .catch(error => console.error('Error checking membership:', error));
    }

    function updateButtonState(button, isMember) {
        const userId = localStorage.getItem('userId');
        const isAdmin = button.dataset.isAdmin === 'true';

        if (isAdmin) {
            button.textContent = 'Edit';
            button.className = 'edit-btn';
        } else if (isMember) {
            button.textContent = 'Leave';
            button.className = 'exit-btn';
        } else {
            button.textContent = 'Join';
            button.className = 'join-btn';
        }
    }

    function handleActionClick(event) {
        const button = event.target;
        const groupId = button.dataset.groupId;
        const isAdmin = button.dataset.isAdmin === 'true';

        if (isAdmin) {
            alert('You are the admin of this group.');
            return;
        }

        const action = button.textContent.toLowerCase();
        const confirmMessage = action === 'join' ? 'Are you sure you want to join this group?' : 'Are you sure you want to leave this group?';

        if (confirm(confirmMessage)) {
            const url = action === 'join' ? `/joinGroup/${groupId}` : `/leaveGroup/${groupId}`;

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateButtonState(button, action === 'join');
                } else {
                    alert(data.message);
                    if (data.message === 'You are already a member of this group.') {
                        updateButtonState(button, true);
                    }
                }
            })
            .catch(error => console.error('Error handling group action:', error));
        }
    }

    //Edit button, click on event handling function
    function handleEditClick(event) {
        const groupId = event.target.dataset.groupId;

        //Open the modal box and fill in the form data
        const modal = document.getElementById('editModal');
        modal.style.display = 'block';

        //Fill the form data in the modal box
        fillEditForm(groupId);
    }

    //Fill the form data in the modal box
    function fillEditForm(groupId) {
        //Retrieve group data from the server and fill it into the form of the modal box
        fetch(`/getGroupDetails/${groupId}`)
            .then(response => response.json())
            .then(group => {
                document.getElementById('groupId').value = groupId;
                document.getElementById('groupName').value = group.GroupName;
                document.getElementById('description').value = group.Description;
                document.getElementById('type').value = group.Type;
                document.getElementById('privacy').value = group.Privacy;
            })
            .catch(error => console.error('Error fetching group details:', error));
    }

    document.querySelector('#editModal .close').addEventListener('click', function() {
        document.getElementById('editModal').style.display = 'none';
    });


    document.getElementById('editForm').addEventListener('submit', function(event) {
        event.preventDefault(); 

        const groupId = document.getElementById('groupId').value;
        const groupName = document.getElementById('groupName').value;
        const description = document.getElementById('description').value;
        const type = document.getElementById('type').value;
        const privacy = document.getElementById('privacy').value;

        fetch(`/updateGroup/${groupId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({
                GroupName: groupName,
                Description: description,
                Type: type,
                Privacy: privacy
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Group updated successfully');
                location.reload();
            } else {
                alert(data.message);
            }
        })
        .catch(error => console.error('Error updating group:', error));

        document.getElementById('editModal').style.display = 'none';
    });

    //Create group button click event
    document.querySelector('.createGroup').addEventListener('click', function() {
        document.getElementById('createModal').style.display = 'block';
    });

    document.querySelector('#createModal .close').addEventListener('click', function() {
        document.getElementById('createModal').style.display = 'none';
    });

    document.getElementById('createForm').addEventListener('submit', function(event) {
        event.preventDefault();

        const groupName = document.getElementById('createGroupName').value;
        const description = document.getElementById('createDescription').value;
        const type = document.getElementById('createType').value;
        const privacy = document.getElementById('createPrivacy').value;
        const adminId = localStorage.getItem('userId');

        fetch('/createGroup', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({
                GroupName: groupName,
                Description: description,
                Type: type,
                Privacy: privacy,
                AdminID: adminId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Group created successfully');
                location.reload();
            } else {
                alert(data.message);
            }
        })
        .catch(error => console.error('Error creating group:', error));

        document.getElementById('createModal').style.display = 'none';
    });
    
});

    document.addEventListener('DOMContentLoaded', function() {
        const studentProfilesLink = document.getElementById('studentProfilesLink');
        const groupManagementLink = document.getElementById('groupManagementLink');

        ////Show Student profiles and hide other sections
        studentProfilesLink.addEventListener('click', function() {
            window.location.href = '/student';
        });

        //Show Group Management and hide other sections
        groupManagementLink.addEventListener('click', function() {
            window.location.href = '/group';
        });


        //Add a click event listener for the Log out button
        const logoutBtn = document.querySelector('.loginOutBtn');
        logoutBtn.addEventListener('click', function() {
            //Clear tokens stored in local storage
            localStorage.removeItem('token');

            //Redirect to/page
            window.location.href = '/';
        });
    });   
    </script>
</body>
</html>